#!/usr/bin/env python

import markdown
import os, sys
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

repo = ""

def wikify(url):
    global repo
    with open(os.path.join(repo,url[1:])) as f:
        kal_code = f.read()
    kal_s = [kal_code] #.split('###\n')
    if len(kal_s) == 1:
        wiki_text = kal_s[0]
    else:
        wiki_text = '\n'.join([kal_s[i] for i in range(1,len(kal_s),2)])
    if url[-4:] == '.css':
        return kal_s
    else:
        html = markdown.markdown(wiki_text).encode('utf-8')
        return ['<html><head><title>', url, '</title></head><body>',
            html,'</body></html>']

def simple_app(environ, start_response):
    try:
        w = wikify(environ['PATH_INFO'])
        status = '200 OK'
        response_headers = [('Content-type', 'text/html')]
        start_response(status, response_headers)
        return w
    except:
        status = '404 Not Found'
        response_headers = [('Content-type', 'text/html')]
        start_response(status, response_headers)
        return ['<html><head><title>Not Found</title></head><body>Not found on server.</body></html>']
        
def main():
    global repo
    repo = sys.argv[1]
    httpd = make_server('', 8000, simple_app)
    print "Serving on port 8000..."
    httpd.serve_forever()
    
if __name__ == '__main__':
    main()